package aod.android.com.bernay.fixing.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hdl.ruler.RulerView;
import com.hdl.ruler.bean.OnBarMoveListener;
import com.hdl.ruler.bean.TimeSlot;
import com.hdl.ruler.utils.DateUtils;
import com.peergine.android.livemulti.pgLibLiveMultiError;
import com.peergine.android.livemulti.pgLibLiveMultiRender;
import com.peergine.android.livemulti.pgLibLiveMultiView;
import com.peergine.plugin.lib.pgLibJNINode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import aod.android.com.bernay.R;
import aod.android.com.bernay.base.BernayBaseActivity;
import aod.android.com.bernay.fixing.adapter.FixingOpenAdapter;
import aod.android.com.bernay.fixing.bean.FixingDatabean;
import aod.android.com.bernay.fixing.bean.P2pOpenFixingDataBean;
import aod.android.com.bernay.fixing.live.pgCallFlow;
import aod.android.com.bernay.fixing.view.PlanningGridView;
import aod.android.com.bernay.http.BernayApi;
import aod.android.com.bernay.http.BernayCallback;
import aod.android.com.bernay.view.DateTimeView;
import chen.lion.hilib.util.LogUtils;
import chen.lion.hilib.view.bind.HiView;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;

public class PlanningActivity extends BernayBaseActivity implements View.OnClickListener {
    @HiView(R.id.title_iv_back)
    ImageView title_iv_back;
    @HiView(R.id.title_tv_name)
    TextView title_tv_name;
    @HiView(R.id.fixng_open_gv)
    PlanningGridView fixng_open_gv;
    @HiView(R.id.fixing_iv_down)
    ImageView fixing_iv_down;
    @HiView(R.id.fixing_iv_check)
    ImageView fixing_iv_check;
    @HiView(R.id.fixing_tv_time)
    TextView fixing_tv_time;
    @HiView(R.id.fixing_video_setting)
    ImageView fixing_video_setting;
    private long currentTimeMillis;
    @HiView(R.id.fixing_hlep_iv)
    ImageView fixing_hlep_iv;
    @HiView(R.id.dataview)
    private DateTimeView mDateTimeView;
    private Integer[] openFixingimg = {
            R.drawable.icon_open_fixng_on,
            R.drawable.icon_open_fixng_off,
            R.drawable.icon_open_fixng_transcribe,
            R.drawable.icon_open_fixng_acquire,
            R.drawable.icon_open_fixng_talk,
            R.drawable.icon_open_fixng_monitor,
            R.drawable.icon_open_fixng_screenshot,
            R.drawable.icon_open_fixng_track,
            R.drawable.icon_open_fixng_gps
    };
    private Integer[] closeFixingimg = {
            R.drawable.icon_close_fixng_on,
            R.drawable.icon_close_fixng_off,
            R.drawable.icon_close_fixng_transcribe,
            R.drawable.icon_close_fixng_acquire,
            R.drawable.icon_close_fixng_talk,
            R.drawable.icon_close_fixng_monitor,
            R.drawable.icon_close_fixng_screenshot,
            R.drawable.icon_close_fixng_track,
            R.drawable.icon_close_fixng_track,
    };

    //设备号
    private String deviceNumber = "";
    //视频信息暂时写死
    //本机号码
    private static String mAccountId = "550100";
    //呼叫号码
    private static String mIvccountId = "550101";
    private int openIs = 0;

    /**
     * P2P相关
     */
    String m_sServerAddr = "connect.peergine.com:7781";
    //akny052901,akny052902,akny052903
    String m_sRenID = "akny052903";
    //呼叫号码
    String m_sCapID = "akny052902";
    //是否在播放
    boolean m_bInited = false;
    //登录状态
    boolean m_bLogin = false;
    pgLibLiveMultiRender m_Live = new pgLibLiveMultiRender();
    @HiView(R.id.layoutVideo)
    LinearLayout m_View;
    SurfaceView m_Wnd = null;


    pgCallFlow m_callFlow = new pgCallFlow() {
        @Override
        protected boolean onMessageSend(String sCallID, String sData) {
            String sDataReq = "Forward?(User){" + sCallID + "}(Msg){" + sData + "}";
            int iErr = m_Live.SvrRequest(sDataReq, "__callflow");
            return (iErr < 0 || iErr == pgLibLiveMultiError.PG_ERR_Normal);
        }

        // Calling event callback methods.
        @Override
        protected void onRequest(String sCallID, String sInfo) {
            try {
                // Show main activity to foreground.
                Intent start = new Intent(getApplicationContext(), PlanningActivity.class);
                start.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(start);
            }
            catch (Exception ex) {
                Log.d("pgLiveMultiRanCall", "onRequest: Show main activity to foreground. ex=" + ex.toString());
            }

            CallFlowDlgShow(sCallID);
            CallFlowReset();
            showError( "Calling from capture: " + sCallID);
        }

        @Override
        protected void onEstablish(String sCallID, String sInfo) {
            CallFlowDlgClose();
            LiveConnect();
            showError("Calling establish.");
        }

        @Override
        protected void onTerminate(String sCallID, int iCode, String sInfo) {
            CallFlowDlgClose();
            CallFlowReset();

            String sTermInfo = m_callFlow.GetTerminateText(iCode);
            showError(sTermInfo);
        }
    };
    private pgLibLiveMultiRender.OnEventListener m_OnEvent = new pgLibLiveMultiRender.OnEventListener() {

        @Override
        public void event(String sAct, String sData, String sCapID) {
            // TODO Auto-generated method stub
            LogUtils.e(sAct);
            if (sAct.equals("VideoStatus")) {
                // Video status report
            } else if (sAct.equals("Notify")) {
                // Receive the notify from capture side
                String sInfo = "Receive notify: data=" + sData;
                showError(sInfo);
            } else if (sAct.equals("Message")) {

                //获取设备推送的信息
                getFixingStatus(sData);
                // Receive the message from render or capture
                String sInfo = "Receive msg: data=" + sData + ", sCapID=" + sCapID;
                showError(sInfo);
            } else if (sAct.equals("Login")) {
                // Login reply
                if (sData.equals("0")) {
                    String sInfo = "Login success";
                    showError(sInfo);
                    m_bLogin = true;
                } else {
                    String sInfo = "Login failed, error=" + sData;
                    showError(sInfo);
                    m_bLogin = false;
                }
            } else if (sAct.equals("Logout")) {
                // Logout
                String sInfo = "Logout";
                showError(sInfo);
                m_bLogin = false;
            } else if (sAct.equals("Connect")) {
                // Connect to capture
                String sInfo = "Connect to capture";
                showError(sInfo);
            } else if (sAct.equals("Disconnect")) {
                // Disconnect from capture
                String sInfo = "Disconnect from capture";
                showError(sInfo);
            } else if (sAct.equals("Reject")) {
                String sInfo = "Reject by capture";
                showError(sInfo);
            } else if (sAct.equals("Offline")) {
                // The capture is offline.
                String sInfo = "Capture offline";
                showError(sInfo);
            } else if (sAct.equals("LanScanResult")) {
                // Lan scan result.
                String sInfo = "Lan scan result: " + sData;
                showError(sInfo);
            } else if (sAct.equals("VideoCamera")) {
                String sInfo = "The picture is save to: " + sData;
                showError(sInfo);
            } else if (sAct.equals("SvrNotify")) {
                CallFlowMessageReceive(sData);
            } else if (sAct.equals("SvrReplyError")) {
                if (sCapID.equals("__callflow")) {
                    CallFlowMessageError(sData);
                }
            }
            Log.d("pgLiveRender", "OnEvent: Act=" + sAct + ", Data=" + sData
                    + ", sCapID=" + sCapID);
        }
    };

    private void getFixingStatus(String sData) {
        if(sData!=null&&!sData.equals("")){
            P2pOpenFixingDataBean p2pOpenFixingDataBean = new P2pOpenFixingDataBean();
            Gson gson = new Gson();
            p2pOpenFixingDataBean = gson.fromJson(sData,P2pOpenFixingDataBean.class);
            if(p2pOpenFixingDataBean.getMsgType().equals("power_status")){
                //如果是开关设备的信息
                String data = p2pOpenFixingDataBean.getData();
                if(data.equals("0")){
                    //设备处于关闭状态
                    openIs = 0;

                }else {
                    //设备处于开启状态
                    openIs = 1;

                }
            }
        }
    }

    private boolean CheckPlugin() {
        if (pgLibJNINode.Initialize(PlanningActivity.this)) {
            pgLibJNINode.Clean();
            return true;
        }
        else {
            showError( "Please import 'pgPluginLib' peergine middle ware!");
            return false;
        }
    }
    @Override
    protected int initLayout() {
        return R.layout.activity_planning;
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void initData() {
        fixing_iv_down.setOnClickListener(this);
        fixing_iv_check.setOnClickListener(this);
        fixing_video_setting.setOnClickListener(this);
        fixing_hlep_iv.setOnClickListener(this);
        title_iv_back.setOnClickListener(this);

//        fixZOrder(mVideoView, mCaptureView);
//        VisualIntercomProxy.initTalkBackSurface(mVideoView,mCaptureView);
        List<TimeSlot> times = new ArrayList<>();
        times.add(new TimeSlot(DateUtils.getTodayStart(System.currentTimeMillis()), DateUtils.getTodayStart(System.currentTimeMillis()) + 60 * 60 * 1000, DateUtils.getTodayStart(System.currentTimeMillis()) + 120 * 60 * 1000));
        times.add(new TimeSlot(DateUtils.getTodayStart(System.currentTimeMillis()), DateUtils.getTodayStart(System.currentTimeMillis()) + 3 * 60 * 60 * 1000, DateUtils.getTodayStart(System.currentTimeMillis()) + 4 * 60 * 60 * 1000));
        if(getIntent().getStringExtra("DeviceNumber")!=null){
            deviceNumber = getIntent().getStringExtra("DeviceNumber");
        }
        //获取设备状态
        getFixingStayus();
        //mVideo.setUp("http://2449.vod.myqcloud.com/2449_43b6f696980311e59ed467f22794e792.f20.mp4", "http://p.qpic.cn/videoyun/0/2449_43b6f696980311e59ed467f22794e792_1/640", "");
        mDateTimeView.getTest();
        fixing_iv_down.setBackgroundResource(R.drawable.icon_fixing_down);
        FixingOpenAdapter fixingOpenAdapter = new FixingOpenAdapter(this, openFixingimg);
        fixng_open_gv.setAdapter(fixingOpenAdapter);
        LogUtils.e(CheckPlugin()+"");
        if (!CheckPlugin()) {
            return;
        }
        m_Live.SetEventListener(m_OnEvent);
        LiveLogin();
        fixng_open_gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();
                switch (position) {
                    //开启设备
                    case 0:
                        openIs = 1;
                        //使用穿透来做开关设备
                        openFixing();

                        //使用推送来连接开关设备
                        closeFixing();
                        bundle.putInt("isOpen",openIs);
                        goActivity(FixinOpenActivity.class,bundle);
                        break;
                    //关闭设备
                    case 1:
                        openIs = 0;
                        closeFixing();
                        bundle.putInt("isOpen",openIs);
                        goActivity(FixinOpenActivity.class,bundle);
                        break;
                    //录制视频
                    case 2:
                        m_Live.MessageSend(m_sCapID, "测试发送");
                        break;
                    //视频调取
                    case 3:
                        bundle.putString("moudel", "3");
                        goActivity(VideoTakenActivity.class, bundle);
                        break;
                    //实时对讲
                    case 4:
                        LiveConnect();
                        break;
                    //车外监听
                    case 5:
                        break;
                    //截图
                    case 6:
                        m_Live.VideoCamera(m_sCapID, 0, "/sdcard/Download/liverender.jpg");
                        break;
                    //行驶轨迹
                    case 7:
                        bundle.putString("moudel", "2");
                        goActivity(VideoTakenActivity.class, bundle);
                        break;
                    //当前位置
                    case 8:
                        break;
                    default:
                        break;
                }
            }
        });

    }

    private void openFixing() {
        P2pOpenFixingDataBean p2pOpenFixingDataBean = new P2pOpenFixingDataBean();
        p2pOpenFixingDataBean.setData(openIs+"");
        p2pOpenFixingDataBean.setMsgType("power_on");
        Gson gson = new Gson();
        String sData = gson.toJson(p2pOpenFixingDataBean,P2pOpenFixingDataBean.class);
        m_Live.MessageSend(m_sCapID, sData);
    }




    private void closeFixing() {
        BernayApi.http().isOpenFixStatus("BD201905240936SS", openIs + "", new BernayCallback() {
            @Override
            public void onJsonData(String json) {
                Gson gson = new Gson();
                FixingDatabean fixingDatabean = gson.fromJson(json, FixingDatabean.class);
                if(fixingDatabean.getStatus()==1){
                    showToast(fixingDatabean.getMsg());
                }else {
                    showToast(fixingDatabean.getMsg());
                }
            }

            @Override
            public void onHttpFailure(IOException e) {

            }
        });


    }

    private void fixZOrder(SurfaceView mVideoView, SurfaceView mCaptureView) {
        mVideoView.setZOrderOnTop(false);
        mCaptureView.setZOrderOnTop(true);
        mCaptureView.setZOrderMediaOverlay(true);
    }
    @Override
    protected void onDestroy() {
        LiveLogout();
        super.onDestroy();

    }
    private void getFixingStayus() {
        BernayApi.http().getFixStatus("BD201905240936SS", new BernayCallback() {
            @Override
            public void onJsonData(String json) {
                Gson gson = new Gson();
                FixingDatabean fixingDatabean = gson.fromJson(json, FixingDatabean.class);
                if(fixingDatabean.getStatus()==1){
                    showToast("获取设备状态成功");
                }else {
                    showToast("获取设备状态失败");
                }
            }

            @Override
            public void onHttpFailure(IOException e) {
                showToast("网络请求失败");
            }
        });


    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fixing_iv_down:
                if (fixng_open_gv.getVisibility() == View.VISIBLE) {
                    fixng_open_gv.setVisibility(View.GONE);
                    fixing_iv_down.setBackgroundResource(R.drawable.icon_fixing_up);
                } else {
                    fixng_open_gv.setVisibility(View.VISIBLE);
                    fixing_iv_down.setBackgroundResource(R.drawable.icon_fixing_down);
                }
                break;
            case R.id.fixing_iv_check:
                Bundle bundle = new Bundle();
                bundle.putString("moudel", "3");
                goActivity(VideoTakenActivity.class, bundle);
                break;
            case R.id.fixing_video_setting:
                goActivity(FixingSettingActivity.class);
                break;
            case R.id.title_iv_back:
                finish();
                break;
            case R.id.fixing_hlep_iv:
                Bundle bundle1 = new Bundle();
                bundle1.putString("moudel", "3");
                goActivity(ExplainActivity.class, bundle1);
                break;
            default:
                break;
        }
    }
    private void LiveConnect() {
        if (!m_bLogin) {
            showError("LiveConnect: This render has no login!");
            return;
        }
        m_Live.Connect(m_sCapID);
        m_Live.VideoStart(m_sCapID, 0, "", m_Wnd);

        String sAudioParam = "";
        m_Live.AudioStart(m_sCapID, 0, sAudioParam);
        m_Live.AudioSyncDelay(m_sCapID, 0, 0);
    }
    private void LiveDisconnect() {
        m_Live.AudioStop(m_sCapID, 0);
        m_Live.VideoStop(m_sCapID, 0);
        m_Live.Disconnect(m_sCapID);
    }
    private void LiveLogin() {
        if (m_bInited) {
            return;
        }
        if (m_callFlow.Initialize(m_sRenID, "", 0, 0) != pgCallFlow.ERROR_OK) {
            showError("LiveLogin: init call flow failed!");
            return;
        }

        String sInitParam = "(Debug){1}";

        int iErr = m_Live.Initialize(m_sRenID, "1234", m_sServerAddr, "", 1, sInitParam, this);
        if (iErr != pgLibLiveMultiError.PG_ERR_Normal) {
            Log.d("pgLiveRander", "LiveStart: Live.Initialize failed! iErr=" + iErr);
            showError("LiveStart: Live.Initialize failed! iErr=" + iErr);
            android.os.Process.killProcess(android.os.Process.myPid());
            return;
        }

        m_Wnd = (SurfaceView) pgLibLiveMultiView.Get("view0");
        m_View.addView(m_Wnd);
        m_Wnd.setVisibility(View.VISIBLE);

        m_bInited = true;
    }

    private void LiveLogout() {
        CallFlowTerminate();
        if (m_Wnd != null) {
            m_View.removeView(m_Wnd);
            pgLibLiveMultiView.Release(m_Wnd);
            m_View = null;
            m_Wnd = null;
            m_Live.Clean();
        }

        m_callFlow.Cleanup();
        m_bLogin = false;
        m_bInited = false;
    }

    private void CallFlowMessageReceive(String sData) {
        pgLibJNINode Node = m_Live.GetNode();
        if (Node != null) {
            Log.d("pgLiveMultiRanCall", "CallFlowMessageReceive: sData=" + sData);
            String sCapID = Node.omlGetContent(sData, "User");
            String sMsg = Node.omlGetContent(sData, "Msg");
            m_callFlow.MessageProc(sCapID, sMsg);
        }
    }

    private void CallFlowMessageError(String sData) {
        int iErrCode = 0;
        try {
            if (!sData.equals("")) {
                iErrCode = Integer.parseInt(sData);
            }
        }
        catch (Exception ex) {
            iErrCode = 0;
        }

        int iMsgErr = 0;
        switch (iErrCode) {
            case pgLibLiveMultiError.PG_ERR_BadObject:
                iMsgErr = pgCallFlow.ERROR_Offline;
                break;

            case pgLibLiveMultiError.PG_ERR_BadParam:
                iMsgErr = pgCallFlow.ERROR_BadParam;
                break;

            case pgLibLiveMultiError.PG_ERR_Timeout:
                iMsgErr = pgCallFlow.ERROR_Timeout;
                break;

            case pgLibLiveMultiError.PG_ERR_Network:
                iMsgErr = pgCallFlow.ERROR_Network;
                break;
            default:
                break;
        }

        m_callFlow.MessageError(iMsgErr);
    }

    private AlertDialog m_dlgCallFlow = null;
    private DialogInterface.OnClickListener m_OnDlgCallFlow = new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            if (which == AlertDialog.BUTTON_POSITIVE) {
                m_callFlow.Accept("");
            }
            else if (which == AlertDialog.BUTTON_NEGATIVE) {
                m_callFlow.Reject("");
            }
            m_dlgCallFlow = null;
        }
    };

    private void CallFlowDlgShow(String sCapID) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Video calling ...");
        builder.setMessage("Calling request from capture: " + sCapID);
        builder.setPositiveButton("Accept", m_OnDlgCallFlow);
        builder.setNegativeButton("Reject", m_OnDlgCallFlow);
        builder.setCancelable(false);
        m_dlgCallFlow = builder.show();
    }

    private void CallFlowDlgClose() {
        if (m_dlgCallFlow != null) {
            m_dlgCallFlow.dismiss();
            m_dlgCallFlow = null;
        }
    }

    private void CallFlowReset() {
        LiveDisconnect();
        m_sCapID = "";
    }

    private void CallFlowEstablish(String sCapID) {
        String m_sCapID = "akny052902";
        LiveConnect();
    }

    private void CallFlowTerminate() {
        LiveDisconnect();
        m_callFlow.Terminate("");
    }




}
